import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store/index";
import api from '@/api/baseApi';
import { Toast } from 'vant';


const routes = [
  {
    path:'/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import(/* webpackChunkName: "default" */ '../views/DetailView.vue')
  },
  {
    path: '/personal',
    name: 'personal',
    component: () => import(/* webpackChunkName: "default" */ '../views/PersonalView.vue')
  },
  {
    path: '/store',
    name: 'store',
    component: () => import(/* webpackChunkName: "default" */ '../views/StoreView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "default" */ '../views/LoginView.vue')
  },
  {
    path: '/updateperson',
    component: () => import(/* webpackChunkName:"other" */'@/views/UpdatePerson.vue')
  }, {
      path: '/:pathMatch(.*)*',
      redirect: '/'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 添加路由守卫
router.beforeEach(async (to, from, next) => {
  // 判断，若进入需要登录的路由，则进行登录判断
  const arr = ['/store', '/personal', '/updateperson']
  if(arr.includes(to.path)){
    // 判断是否登录，若登录则vuex中记录登录信息
    const isLogin = store.state.isLogin
    console.log('进入路由守卫', isLogin);
    if(isLogin){
      next()
      return
    }
    if(isLogin == false){
      Toast('小主，请先登录哦~')
      next('/login')
      return
    }
    if(isLogin == null){
      // 其实这一步相当于重新处理vuex，刷新完根据state状态值重新获取数据
      try{
        // 验证登录,使用的是接口方式验证
        const { code, data } = await api.checkLogin()
        if(+code !== 0){
          Toast('小主，请先登录哦~')
          next('/login')
          return
        }
        store.commit('changeIsLogin', true);
        store.commit('changeInfo', data);
        next();
      }catch(e){}
      return 
    }
  }
  // 其余的直接放行
  next()
})

export default router
